<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author laz
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <!-- <a-button type="default" @click="handleExport()">
          <Icon icon="ant-design:download-outlined" /> {{ t('导出') }}
        </a-button>
        <a-button type="default" @click="handleImport()">
          <Icon icon="ant-design:upload-outlined" /> {{ t('导入') }}
        </a-button>
        <a-button type="primary" @click="handleForm({})" v-auth="'information:dailySigns:edit'">
          <Icon icon="fluent:add-12-filled" /> {{ t('新增') }}
        </a-button> -->
        <a-button type="default" @click="handlePullClick" :disabled="isPulling">
          <Icon icon="ant-design:download-outlined" /> {{ t('拉取') }}
        </a-button>
        <a-button type="default" @click="handleUpdateClick" :disabled="isUpdate">
          <Icon icon="ant-design:pull-request-outlined" /> {{ t('更新') }}
        </a-button>
      </template>
      <template #firstColumn="{ record }">
        {{ record.productName }}
        <!-- <a @click="handleForm({ tid: record.tid })">
          {{ record.productName }}
        </a> -->
      </template>
      <template #state="{ record }">
        <!-- 判断订单状态 订单状态 1-待付款 2-待发货 3-待收货 4-已完成 5-已取消 6-待成团 -->
        <!-- <el-tag v-if="record.state == 1" type="info">{{ t('待付款') }}</el-tag>
        <el-tag v-else-if="record.state == 2" type="success">{{ t('待发货') }}</el-tag>
        <el-tag v-else-if="record.state == 3" type="warning">{{ t('待收货') }}</el-tag>
        <el-tag v-else-if="record.state == 4" type="success">{{ t('已完成') }}</el-tag>
        <el-tag v-else-if="record.state == 5" type="error">{{ t('已取消') }}</el-tag>
        <el-tag v-else-if="record.state == 6" type="info">{{ t('待成团') }}</el-tag> -->
        <el-tag v-if="record.state == 1" type="info">{{ t('待支付') }}</el-tag>
        <el-tag v-else type="success">{{ t('已支付') }}</el-tag>
        <!-- {{ record.productName }} -->
      </template>

      <template #paymentTime="{ record }">
        {{ record.paymentTime ? record.paymentTime : record.createTime }}
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" :phone="phone" />
    <!-- 全屏加载蒙层 -->
    <div v-if="showLoading" class="loading-overlay">
      <div class="loading-content">
        <Spin tip="正在获取数据，请稍后..." size="large" />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup name="ViewsInformationHistoryOrdersList">
  import { unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { historyOrdersDelete, historyOrdersListData } from '/@/api/information/historyOrders';
  import {
    historyOrdersSave,
    historyOrdersInsert,
    historyOrdersUpdate,
    getProducts,
  } from '/@/api/information/historyOrders';
  import { useDrawer } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { FormProps } from '/@/components/Form';
  import InputForm from './form.vue';
  import { useUserStore } from '/@/store/modules/user';
  import { ref } from 'vue';
  import { getMappingId } from '/@/api/sys/desktopApi';
  import axios from 'axios';
  import { Modal } from 'ant-design-vue';
  import { Spin } from 'ant-design-vue';
  import dayjs, { Dayjs } from 'dayjs'; // 导入 Dayjs 类型

  // 获取用户
  const currentUser = useUserStore().getUserInfo;
  const phone = currentUser.loginCode;
  const userId = currentUser.userCode;
  const { t } = useI18n('information.dailySigns');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const mappingId = ref({});

  // 新增状态变量
  const isPulling = ref(false);
  const isUpdate = ref(false); // 控制按钮禁用状态
  const showLoading = ref(false);

  const getTitle = {
    icon: meta.icon || 'ant-design:book-outlined',
    value: meta.title || t('日常体征管理'),
  };

  // 计算默认日期范围：今天到三个月前
  const today = dayjs();
  const oneYearAgo = today.subtract(1, 'year');

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      {
        label: t('服务名称'),
        field: 'productNameLike',
        component: 'Input',
      },
      {
        label: t('服务商名称'),
        field: 'shopNameLike',
        component: 'Input',
      },
      {
        label: t('创建时间'),
        field: 'dateRange',
        component: 'RangePicker',
        required: true,
        componentProps: {
          format: 'YYYY-MM-DD',
          // 【修改】: 增加健壮性检查
          disabledDate: (current: Dayjs) => {
            // 规则1: 不能选择今天之后的日期
            if (current && current > dayjs().endOf('day')) {
              return true;
            }

            try {
              // 获取表单中已选的日期
              // 使用 try...catch 块来捕获可能的 getForm() 早期调用错误
              const formModel = getForm()?.getFieldsValue();

              // 【关键修复】: 在访问 .dateRange 之前，必须检查 formModel 是否存在
              if (!formModel || !formModel.dateRange) {
                return false; // 如果表单模型或dateRange不存在，则不施加任何限制
              }

              const selectedDates = formModel.dateRange;

              // 规则2: 当用户已经选择了一个日期后，动态限制另一个日期的范围
              if (selectedDates.length === 1) {
                const referenceDate = selectedDates[0]; // 将已选的日期作为参考点

                // 限制结束日期不能比开始日期晚超过1年
                const maxDate = referenceDate.add(1, 'year');
                if (current > maxDate) return true;

                // 限制开始日期不能比结束日期早超过1年
                const minDate = referenceDate.subtract(1, 'year');
                if (current < minDate) return true;
              }
            } catch (error) {
              // 在组件挂载初期，getForm() 可能尚未准备好，会抛出错误
              // 在这种情况下，我们不施加任何限制，让组件正常渲染
              // console.warn('getForm() is not ready yet:', error);
              return false;
            }

            return false;
          },
        },
        defaultValue: [oneYearAgo, today],
      },
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('服务名称'),
      dataIndex: 'shopName',
      key: 'a.shopName',
      sorter: true,
      width: 230,
      align: 'center',
      slot: 'firstColumn',
    },
    {
      title: t('服务商名称'),
      dataIndex: 'shopName',
      key: 'a.shopName',
      sorter: true,
      width: 230,
      align: 'center',
    },
    // { title: t('金额'), dataIndex: 'price', key: 'a.price', sorter: true, width: 130, align: 'center' },
    {
      title: t('创建时间'),
      dataIndex: 'paymentTime',
      key: 'a.paymentTime',
      sorter: true,
      width: 230,
      align: 'center',
      slot: 'paymentTime',
    },
    {
      title: t('订单状态'),
      dataIndex: 'state',
      key: 'a.state',
      sorter: true,
      width: 130,
      align: 'center',
      slot: 'state',
    },
    {
      title: t('服务类型'),
      dataIndex: 'classifyName',
      key: 'a.classifyName',
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('来源平台'),
      dataIndex: 'sourcePlatform',
      key: 'a.classifyName',
      sorter: true,
      width: 130,
      align: 'center',
    },
  ];

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, getForm }] = useTable({
    api: historyOrdersListData,
    // 【修改3】: 优化 beforeFetch 逻辑
    beforeFetch: (params) => {
      const newParams = { ...params }; // 创建一个新对象，避免直接修改原params
      // 处理日期范围参数
      if (newParams.dateRange && newParams.dateRange.length === 2) {
        const start = dayjs(newParams.dateRange[0]);
        const end = dayjs(newParams.dateRange[1]);
        console.log('开始时间:', start.format('YYYY-MM-DD HH:mm:ss'));
        console.log('结束时间:', end.format('YYYY-MM-DD HH:mm:ss'));

        // 检查日期范围是否超过1年(带日期的一年，不是只比较月份)
        const oneYearAfterStart = start.add(1, 'year');
        // 2. 判断结束日期是否严格大于1年后的日期
        //    如果 end > oneYearAfterStart，说明时间跨度超过了1年
        if (end.isAfter(oneYearAfterStart)) {
          showMessage('查询时间范围不能超过1年');
          return Promise.reject(); // 阻止本次API请求
        }
        // const diffMonths = end.diff(start, 'month');
        // console.log('时间间隔:', diffMonths);
        // if (diffMonths > 3) {
        //   showMessage('查询时间范围不能超过3个月');
        //   // 返回 Promise.reject() 可以阻止本次查询
        //   return Promise.reject();
        // }

        // 转换为API需要的格式，确保时分秒也被包含
        newParams.beginCreateTime = start.format('YYYY-MM-DD 00:00:00');
        newParams.endCreateTime = end.format('YYYY-MM-DD 23:59:59');
      }
      // 删除原始的dateRange参数，避免干扰后端
      delete newParams.dateRange;

      newParams.phone = currentUser.loginCode;
      return newParams;
    },
    columns: tableColumns,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
  });

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  // 新增：按钮点击事件处理
  function handlePullClick() {
    // 禁用按钮
    isPulling.value = true;

    // 显示确认对话框
    Modal.confirm({
      title: '授权确认',
      content: '您将授权我们从哈医大健康平台获取您的随访记录，是否继续？',
      onOk: async () => {
        // 用户确认后执行实际的拉取操作
        await handlePull();
      },
      onCancel: () => {
        // 用户取消后恢复按钮状态
        isPulling.value = false;
        Modal.destroyAll();
      },
    });
  }

  // 新增：按钮点击事件处理
  function handleUpdateClick() {
    // 禁用按钮
    isUpdate.value = true;

    // 显示确认对话框
    Modal.confirm({
      title: '授权确认',
      content: '您将授权我们从颐乐居驿站云和众阳云健康获取您的服务记录更新状态，是否继续？',
      onOk: async () => {
        // 用户确认后执行实际的更新操作
        await handleUpdate();
      },
      onCancel: () => {
        // 用户取消后恢复按钮状态
        isUpdate.value = false;
        Modal.destroyAll();
      },
    });
  }

  // 修改：实际的拉取数据逻辑
  async function handlePull() {
    try {
      // const resInsert1 = await historyOrdersInsert({});
      // 显示全屏加载蒙层
      showLoading.value = true;

      // 获取映射ID
      mappingId.value = await getMappingId({
        phone: userId,
      });
      const resProducts = await getProducts({
        page: 1,
        pageSize: 100,
        productName: '随访',
        sourcePlatform: '哈医大',
      });
      console.log('产品列表:', resProducts.data);

      const productList = resProducts.data.list;

      // 拉取数据
      const platformName = 'platformDId'; // 哈医大
      const myPlatformName = 'platformId'; // buyerUserID
      const id_1 = mappingId.value[platformName];
      const buyerUserId = mappingId.value[myPlatformName];

      if (!id_1) {
        showMessage('用户不在该平台');
        return;
      }
      const res = await axios.post(
        `https://hgdzhyypt.msuncloud.cn:20145/main/execute-task`,
        { user_id: id_1, task_name: 'hyd_intelligent_order' },
        {
          timeout: 100000,
          headers: {
            'Content-Type': 'application/json',
          },
        },
      );

      console.log('API 响应:', res.data);
      const orderList = res.data.data.answer;
      // const orderList = JSON.parse(
      //   '[\n    {\n        "weight": "75.2",\n        "heartRate": "72",\n        "breathe": "18",\n        "systolicPressure": "118",\n        "diastolicPressure": "78",\n        "temperature": "37.0",\n        "bloodSugar": "5.5",\n        "createTime": "2025-07-24 08:30:15"\n    },\n    {\n        "weight": "75.1",\n        "heartRate": "70",\n        "breathe": "17",\n        "systolicPressure": "120",\n        "diastolicPressure": "80",\n        "temperature": "37.0",\n        "bloodSugar": "5.3",\n        "createTime": "2025-07-25 08:32:05"\n    },\n    {\n        "weight": "75.3",\n        "heartRate": "75",\n        "breathe": "18",\n        "systolicPressure": "122",\n        "diastolicPressure": "79",\n        "temperature": "37.0",\n        "bloodSugar": "5.8",\n        "createTime": "2025-07-26 08:29:11"\n    },\n    {\n        "weight": "75.0",\n        "heartRate": "69",\n        "breathe": "17",\n        "systolicPressure": "119",\n        "diastolicPressure": "77",\n        "temperature": "37.0",\n        "bloodSugar": "5.4",\n        "createTime": "2025-07-27 08:31:00"\n    },\n    {\n        "weight": "74.9",\n        "heartRate": "71",\n        "breathe": "18",\n        "systolicPressure": "121",\n        "diastolicPressure": "81",\n        "temperature": "37.0",\n        "bloodSugar": "5.6",\n        "createTime": "2025-07-28 08:33:40"\n    },\n    {\n        "weight": "75.2",\n        "heartRate": "73",\n        "breathe": "17",\n        "systolicPressure": "117",\n        "diastolicPressure": "78",\n        "temperature": "37.0",\n        "bloodSugar": "5.7",\n        "createTime": "2025-07-29 08:30:50"\n    },\n    {\n        "weight": "75.4",\n        "heartRate": "70",\n        "breathe": "18",\n        "systolicPressure": "120",\n        "diastolicPressure": "80",\n        "temperature": "37.0",\n        "bloodSugar": "5.3",\n        "createTime": "2025-07-30 08:28:19"\n    },\n    {\n        "weight": "75.3",\n        "heartRate": "72",\n        "breathe": "17",\n        "systolicPressure": "122",\n        "diastolicPressure": "79",\n        "temperature": "37.0",\n        "bloodSugar": "5.5",\n        "createTime": "2025-07-31 08:34:02"\n    },\n    {\n        "weight": "75.1",\n        "heartRate": "68",\n        "breathe": "18",\n        "systolicPressure": "118",\n        "diastolicPressure": "76",\n        "temperature": "37.0",\n        "bloodSugar": "5.2",\n        "createTime": "2025-08-01 08:31:22"\n    },\n    {\n        "weight": "75.0",\n        "heartRate": "71",\n        "breathe": "17",\n        "systolicPressure": "119",\n        "diastolicPressure": "78",\n        "temperature": "37.0",\n        "bloodSugar": "5.4",\n        "createTime": "2025-08-02',
      // );
      // console.log('report:', report);

      // 处理返回的订单数据，匹配shopName和productName，给id赋值
      // 建立订单与商品的对应关系
      const matchedResult = orderList.map((order) => {
        // 分割订单的shopName，按 '/' 拆分
        const shopNameParts = order.shopName.split('/');
        // 提取第2个部分（索引1），若不足则记为null
        const targetShopName = shopNameParts.length >= 2 ? shopNameParts[1] : null;

        // 找到resProducts中shopName匹配的商品
        const matchedProducts = targetShopName
          ? productList.filter((product) => product.shopName === targetShopName)
          : [];

        return {
          createTime: order.createTime,
          buyerUserId: buyerUserId,
          customerPhone: phone,
          receivePhone: phone,
          shopName: targetShopName,
          productName: '随访',
          productId: matchedProducts[0]?.productId || '',
          shopId: matchedProducts[0]?.shopId || '',
        };
      });
      console.log('matchedResult:', matchedResult);
      const resInsert = await historyOrdersInsert(matchedResult);
      // 成功反馈
      showMessage('数据拉取成功');
    } catch (e) {
      console.error('拉取失败:', e);
      // 失败反馈
      showMessage('数据拉取失败，请稍后重试');
    } finally {
      // 隐藏加载蒙层
      showLoading.value = false;
      // 恢复按钮状态
      isPulling.value = false;
      // 关闭确认对话框
      Modal.destroyAll();
      // close();
      // 刷新表格
      reload();
    }
  }

  // 修改：实际的更新数据逻辑
  async function handleUpdate() {
    try {
      // 显示全屏加载蒙层
      showLoading.value = true;
      // 获取映射ID
      const resInsert = await historyOrdersUpdate({ buyerUserId: userId });
      // 成功反馈
      showMessage('数据更新成功');
    } catch (e) {
      console.error('更新失败:', e);
      // 失败反馈
      showMessage('数据更新失败，请稍后重试');
    } finally {
      // 隐藏加载蒙层
      showLoading.value = false;
      // 恢复按钮状态
      isUpdate.value = false;
      // 关闭确认对话框
      Modal.destroyAll();
      // close();
      // 刷新表格
      reload();
    }
  }

  // async function handleDelete(record: Recordable) {
  //   const params = { tid: record.tid };
  //   const res = await historyOrdersDelete(params);
  //   showMessage(res.message);
  //   handleSuccess(record);
  // }

  function handleSuccess(record: Recordable) {
    reload({ record });
  }
</script>
<style scoped>
  /* 全屏加载蒙层样式 */
  .loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
  }

  .loading-content {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    text-align: center;
  }
</style>
